<template>
  <el-dialog v-model="visible" title="分享" width="500px">
    <h3>复制链接分享</h3>
    <div class="wrapper">
      <span @click="doCopy">{{ imageUrl }}</span>
    </div>
    <h3>手机扫码查看</h3>
    <div class="wrapper">
      <img @click="doCopy" :src="qrcodeUrl" alt="二维码" width="200px" height="200px" />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, toRef, watch, watchEffect } from 'vue';
// @ts-ignore
import QRCode from "qrcode";
import { ElMessage } from 'element-plus';
import useClipboard from 'vue-clipboard3'

const { toClipboard } = useClipboard();

// 从父组件传来的图像 URL
const prop = defineProps({ imageUrl: String });
const imageUrl = toRef(prop, "imageUrl");

// 是否可见
const visible = ref(false);

// 打开弹窗
const openDialog = () => {
  visible.value = true;

  // 生成二维码
  QRCode.toDataURL(imageUrl.value)
  .then((url: any) => {
    qrcodeUrl.value = url;
  })
  .catch((err: any) => {
    console.error(err);
    ElMessage.error("生成二维码失败: " + err.message);
  });
};

// 暴露函数给父组件
defineExpose({
  openDialog,
});

const qrcodeUrl = ref("");

const doCopy = async () => {
  try {
    await toClipboard(imageUrl.value as string)
    ElMessage.success('复制成功')
  } catch (e) {
    ElMessage.error('复制失败')
  }
}

</script>

<style scoped>
.wrapper {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  * {
    cursor: pointer;
  }

}
</style>